package com.ygxsk.carhome.listener;


import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.subjects.PublishSubject;

/**
 * Created by amitshekhar on 06/02/17.
 */

public class RxBus {

    //2018年02月09日的第一种写法，个是从
   /* public RxBus() {
    }

    private PublishSubject<Object> bus = PublishSubject.create();

    public void send(Object o) {
        bus.onNext(o);
    }

    public Observable<Object> toObservable() {
        return bus;
    }

    public boolean hasObservers() {
        return bus.hasObservers();
    }*/


    //第二种写法 这种是大管家商城里摘抄过来的
    private static volatile RxBus mInstance;

    private final PublishSubject bus;

    public RxBus() {
        bus = PublishSubject.create();
    }

    public static RxBus getInstance() {

        RxBus rxBus2 = mInstance;
        if (mInstance == null) {
            synchronized (RxBus.class) {
                rxBus2 = mInstance;
                if (mInstance == null) {
                    rxBus2 = new RxBus();
                    mInstance = rxBus2;
                }
            }
        }

        return rxBus2;
    }

    /**
     * 发送消息
     *
     * @param object
     */
    public void post(Object object) {

        bus.onNext(object);

    }

    //2018年03月26日添加

    /**
     * @date 2018/3/26 0026
     * @auther itchenqi
     * @description 是否已有观察者, 还未用到。
     */
    public boolean hasObservers() {
        return bus.hasObservers();
    }

    public void unSubscribe(Object o) {

        //if (bu)

    }

    /**
     * 接收消息 根据传递的 eventType 类型返回特定类型(eventType)的 被观察者
     *
     * @param eventType
     * @param <T>
     * @return
     */
    public <T> Observable<T> toObserverable(Class<T> eventType) {
        return bus.ofType(eventType);
    }

    //  这里感谢小鄧子的提醒: ofType = filter + cast
    //  return bus.filter(new Func1<Object, Boolean>() {
    //      @Override
    //      public Boolean call(Object o) {
    //          return eventType.isInstance(o);
    //      }
    //  }) .cast(eventType);
}
